24.7.4. @ConfigurationProperties Validation
24.7.4. @ConfigurationProperties校验
Spring Boot会尝试校验@ConfigurationProperties类,只要它们标注了Spring的@Validated。你可以在你的配置类中直接使用JSR-303 javax.validation约束标注。确保在你的类路径中存在适用的JSR-303实现,再添加约束标注在你的域中:
@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {
    @NotNull
    private InetAddress remoteAddress;
    // ... getters and setters
}
注 你也可以通过标注@Bean方法触发验证,用@Validated创建配置属性。
尽管在绑定后,内嵌属性也会被验证,但还是把相关的域标注上@Valid不失为一种良好的实践。这确保了即使没有找到内嵌属性,验证还是会被触发。下面的例子建立在之前的AcmeProperties示例之上:
为了校验内嵌属性的值,你需要使用@Valid注解关联的字段以触发它的校验,例如,建立在上面的FooProperties示例之上:
@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {
    @NotNull
    private InetAddress remoteAddress;
    @Valid
    private final Security security = new Security(); 
    // ... getters and setters
    public static class Security {
        @NotEmpty
        public String username;
        // ... getters and setters
    }
}
你也可以通过创建一个叫做configurationPropertiesValidator的bean来添加自定义的Spring Validator。@Bean方法需要声明为static,因为配置属性校验器在应用程序生命周期中创建的比较早,将@Bean方法声明为static允许该bean在创建时不需要实例化@Configuration类,从而避免了早期实例化(early instantiation)的所有问题。相关的示例可以看这里。
注 spring-boot-actuator模块包含一个暴露所有@ConfigurationProperties beans的端点(endpoint),通过浏览器打开/actuator/configprops进行浏览,或使用等效的JMX端点,具体参考[Production ready features](../V. Spring Boot Actuator/50. Endpoints.md)。